<template>
  <div class="mqtt-client module-container">
    <div class="module-header">
      <h2>{{ $t('mqtt.client.title') }}</h2>
      <p class="module-description">{{ $t('mqtt.client.description') }}</p>
    </div>

    <div class="module-content">
      <el-row :gutter="20">
        <!-- 左侧：连接和订阅配置 -->
        <el-col :span="6">
          <el-card class="connection-card">
            <div slot="header">
              <span>{{ $t('mqtt.client.connectionSettings') }}</span>
              <ConnectionStatus :connected="isConnected" style="float: right" />
            </div>
            
            <el-form label-position="top" size="small">
              <el-form-item :label="$t('mqtt.client.brokerAddress')">
                <el-input
                  v-model="connectionConfig.url"
                  placeholder="mqtt://broker.hivemq.com:1883"
                  :disabled="isConnected"
                />
              </el-form-item>
              
              <el-form-item :label="$t('mqtt.clientId')">
                <el-input
                  v-model="connectionConfig.clientId"
                  :placeholder="$t('mqtt.client.autoGenerateId')"
                  :disabled="isConnected"
                />
              </el-form-item>
              
              <el-form-item :label="$t('mqtt.username')">
                <el-input
                  v-model="connectionConfig.username"
                  :placeholder="$t('common.optional')"
                  :disabled="isConnected"
                />
              </el-form-item>
              
              <el-form-item :label="$t('mqtt.password')">
                <el-input
                  v-model="connectionConfig.password"
                  type="password"
                  :placeholder="$t('common.optional')"
                  :disabled="isConnected"
                />
              </el-form-item>
              
              <el-form-item>
                <el-button
                  v-if="!isConnected"
                  type="primary"
                  @click="connect"
                  block
                  size="small"
                >
                  {{ $t('mqtt.connect') }}
                </el-button>
                <el-button
                  v-else
                  type="danger"
                  @click="disconnect"
                  block
                  size="small"
                >
                  {{ $t('mqtt.disconnect') }}
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <el-card class="subscription-card" style="margin-top: 20px">
            <div slot="header">
              <span>{{ $t('mqtt.client.subscriptions') }}</span>
            </div>
            
            <el-form @submit.native.prevent="subscribe" size="small">
              <el-form-item :label="$t('mqtt.topic')">
                <el-input
                  v-model="subscribeForm.topic"
                  placeholder="topic/example/#"
                  :disabled="!isConnected"
                  @keyup.enter="subscribe"
                />
              </el-form-item>
              
              <el-form-item :label="$t('mqtt.qos')">
                <el-radio-group v-model="subscribeForm.qos" :disabled="!isConnected" size="small">
                  <el-radio :label="0">0</el-radio>
                  <el-radio :label="1">1</el-radio>
                  <el-radio :label="2">2</el-radio>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item>
                <el-button
                  type="primary"
                  @click="subscribe"
                  :disabled="!isConnected || !subscribeForm.topic"
                  block
                  size="small"
                >
                  {{ $t('mqtt.subscribe') }}
                </el-button>
              </el-form-item>
            </el-form>

            <div class="subscriptions-list">
              <h4>{{ $t('mqtt.client.subscribedTopics') }}</h4>
              <div class="subscription-tags">
                <el-tag
                  v-for="sub in subscriptions"
                  :key="sub.id"
                  closable
                  @close="unsubscribe(sub.topic)"
                  size="small"
                  style="margin: 2px"
                >
                  {{ sub.topic }} (QoS: {{ sub.qos }})
                </el-tag>
              </div>
              <p v-if="subscriptions.length === 0" class="empty-text">
                {{ $t('mqtt.client.noSubscriptions') }}
              </p>
            </div>
          </el-card>
        </el-col>

        <!-- 中间：消息列表 -->
        <el-col :span="12">
          <el-card class="messages-card">
            <div slot="header" class="messages-header">
              <span>{{ $t('mqtt.client.messages') }}</span>
              <div class="header-actions">
                <el-input
                  v-model="messageFilter"
                  :placeholder="$t('mqtt.client.filterTopic')"
                  prefix-icon="el-icon-search"
                  size="mini"
                  style="width: 150px; margin-right: 10px"
                  clearable
                />
                <el-checkbox v-model="autoScroll" size="small">{{ $t('common.autoScroll') }}</el-checkbox>
                <el-button size="mini" @click="clearMessages" icon="el-icon-delete">{{ $t('common.clear') }}</el-button>
              </div>
            </div>

            <div class="messages-list" ref="messagesList">
              <div
                v-for="msg in filteredMessages"
                :key="msg.id"
                class="message-item"
                :class="{ 'message-sent': msg.type === 'sent', 'message-received': msg.type === 'received' }"
              >
                <div class="message-header">
                  <div class="message-meta">
                    <el-tag size="mini" :type="msg.type === 'sent' ? 'success' : 'primary'">
                      {{ msg.type === 'sent' ? $t('mqtt.client.sent') : $t('mqtt.client.received') }}
                    </el-tag>
                    <el-tag size="mini" type="info">{{ msg.topic }}</el-tag>
                    <span class="message-qos" v-if="msg.qos !== undefined">QoS: {{ msg.qos }}</span>
                  </div>
                  <span class="message-time">{{ formatTime(msg.timestamp) }}</span>
                </div>
                <div class="message-body">
                  <pre>{{ formatMessage(msg.message) }}</pre>
                </div>
                <div class="message-actions">
                  <el-button size="mini" @click="copyMessage(msg.message)" icon="el-icon-copy-document">{{ $t('tools.jsonFormatter.copy') }}</el-button>
                  <el-button size="mini" @click="replyToMessage(msg)" icon="el-icon-refresh" v-if="msg.type === 'received'">{{ $t('common.reply') }}</el-button>
                </div>
              </div>
              <div v-if="allMessages.length === 0" class="empty-state">
                <i class="el-icon-chat-line-round"></i>
                <p>{{ $t('mqtt.client.noMessages') }}</p>
                <p class="empty-hint">{{ $t('mqtt.client.noMessages') }}</p>
              </div>
            </div>
            
            <!-- 消息统计 -->
            <div class="message-stats">
              <span>{{ $t('common.total') }}: {{ allMessages.length }}</span>
              <span>{{ $t('mqtt.client.sent') }}: {{ sentCount }}</span>
              <span>{{ $t('mqtt.client.received') }}: {{ receivedCount }}</span>
            </div>
          </el-card>
        </el-col>

        <!-- 右侧：发布消息 -->
        <el-col :span="6">
          <el-card class="publish-card">
            <div slot="header">
              <span>{{ $t('mqtt.client.publishMessage') }}</span>
            </div>
            
            <el-form label-position="top" size="small">
              <el-form-item :label="$t('mqtt.topic')">
                <el-autocomplete
                  v-model="publishForm.topic"
                  :fetch-suggestions="queryTopics"
                  placeholder="topic/example"
                  :disabled="!isConnected"
                  style="width: 100%"
                />
              </el-form-item>
              
              <el-form-item :label="$t('mqtt.message')">
                <el-input
                  type="textarea"
                  v-model="publishForm.message"
                  :rows="8"
                  :placeholder="$t('mqtt.message')"
                  :disabled="!isConnected"
                />
              </el-form-item>
              
              <el-form-item :label="$t('common.options')">
                <el-row>
                  <el-col :span="14">
                    <span style="font-size: 12px;">QoS:</span>
                    <el-radio-group v-model="publishForm.qos" :disabled="!isConnected" size="mini">
                      <el-radio :label="0">0</el-radio>
                      <el-radio :label="1">1</el-radio>
                      <el-radio :label="2">2</el-radio>
                    </el-radio-group>
                  </el-col>
                  <el-col :span="10">
                    <el-checkbox v-model="publishForm.retain" :disabled="!isConnected" size="small">{{ $t('mqtt.retain') }}</el-checkbox>
                  </el-col>
                </el-row>
              </el-form-item>
              
              <el-form-item>
                <el-button
                  type="primary"
                  @click="publish"
                  :disabled="!isConnected || !publishForm.topic || !publishForm.message"
                  block
                  size="small"
                  icon="el-icon-s-promotion"
                >
                  {{ $t('mqtt.publish') }}
                </el-button>
                <el-button 
                  @click="formatJson" 
                  :disabled="!publishForm.message"
                  block
                  size="small"
                  style="margin-top: 10px"
                  icon="el-icon-magic-stick"
                >
                  {{ $t('common.formatJson') }}
                </el-button>
              </el-form-item>
            </el-form>

            <!-- 快速发布模板 -->
            <div class="quick-templates">
              <h4>{{ $t('mqtt.client.messageTemplate') }}</h4>
              <div class="template-buttons">
                <el-button
                  v-for="template in messageTemplates"
                  :key="template.name"
                  size="mini"
                  @click="applyTemplate(template)"
                  style="margin: 2px"
                >
                  {{ template.name }}
                </el-button>
              </div>
            </div>

            <!-- 最近发布 -->
            <div class="recent-publish">
              <h4>{{ $t('mqtt.client.publishHistory') }} <el-button size="mini" @click="clearRecentPublish" style="float: right">{{ $t('common.clear') }}</el-button></h4>
              <div class="recent-list">
                <div
                  v-for="(item, index) in recentPublish"
                  :key="index"
                  class="recent-item"
                  @click="loadFromHistory(item)"
                >
                  <div class="recent-topic">
                    <i class="el-icon-notebook-2"></i> {{ item.topic }}
                  </div>
                  <div class="recent-message">{{ truncateMessage(item.message) }}</div>
                </div>
              </div>
              <p v-if="recentPublish.length === 0" class="empty-text">
                {{ $t('mqtt.client.noMessages') }}
              </p>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import ConnectionStatus from '@/components/ConnectionStatus.vue'

export default {
  name: 'MqttClient',
  components: {
    ConnectionStatus
  },
  data() {
    return {
      subscribeForm: {
        topic: '',
        qos: 0
      },
      publishForm: {
        topic: '',
        message: '',
        qos: 0,
        retain: false
      },
      messageFilter: '',
      autoScroll: true,
      recentPublish: [],
      allMessages: [],
      messageTemplates: [
        { name: '测试消息', topic: 'test/topic', message: '{"type": "test", "timestamp": ' + Date.now() + '}' },
        { name: '心跳包', topic: 'heartbeat', message: '{"type": "ping", "time": ' + Date.now() + '}' },
        { name: '状态更新', topic: 'status/update', message: '{"status": "online", "data": {}}' },
        { name: '传感器数据', topic: 'sensor/data', message: '{"temperature": 25.5, "humidity": 60}' }
      ]
    }
  },
  computed: {
    ...mapState('mqtt', [
      'isConnected',
      'connectionConfig',
      'subscriptions',
      'messages'
    ]),
    
    filteredMessages() {
      // 合并发送和接收的消息
      const combinedMessages = [...this.allMessages]
      
      if (!this.messageFilter) return combinedMessages
      
      return combinedMessages.filter(msg =>
        msg.topic.toLowerCase().includes(this.messageFilter.toLowerCase()) ||
        msg.message.toLowerCase().includes(this.messageFilter.toLowerCase())
      )
    },
    
    sentCount() {
      return this.allMessages.filter(m => m.type === 'sent').length
    },
    
    receivedCount() {
      return this.allMessages.filter(m => m.type === 'received').length
    }
  },
  watch: {
    messages: {
      handler(newMessages) {
        // 将接收到的消息添加到 allMessages
        newMessages.forEach(msg => {
          if (!this.allMessages.find(m => m.id === msg.id)) {
            this.allMessages.push({
              ...msg,
              type: 'received'
            })
          }
        })
        
        if (this.autoScroll) {
          this.$nextTick(() => {
            this.scrollToBottom()
          })
        }
      },
      deep: true
    }
  },
  methods: {
    ...mapActions('mqtt', [
      'connect',
      'disconnect',
      'subscribe',
      'unsubscribe',
      'publish',
      'updateConnectionConfig',
      'clearMessages'
    ]),
    
    async subscribe() {
      if (!this.subscribeForm.topic) {
        this.$message.warning('请输入订阅主题')
        return
      }
      
      const result = await this.$store.dispatch('mqtt/subscribe', {
        topic: this.subscribeForm.topic,
        qos: this.subscribeForm.qos
      })
      
      if (result.success) {
        this.$message.success('订阅成功')
        this.subscribeForm.topic = ''
      } else {
        this.$message.error('订阅失败: ' + result.message)
      }
    },
    
    async publish() {
      if (!this.publishForm.topic || !this.publishForm.message) {
        this.$message.warning('请输入主题和消息')
        return
      }
      
      const result = await this.$store.dispatch('mqtt/publish', {
        topic: this.publishForm.topic,
        message: this.publishForm.message,
        qos: this.publishForm.qos,
        retain: this.publishForm.retain
      })
      
      if (result.success) {
        this.$message.success('发布成功')
        
        // 将发送的消息添加到消息列表
        this.allMessages.push({
          id: `sent_${Date.now()}`,
          type: 'sent',
          topic: this.publishForm.topic,
          message: this.publishForm.message,
          qos: this.publishForm.qos,
          timestamp: new Date().toISOString()
        })
        
        this.addToRecentPublish()
        
        if (this.autoScroll) {
          this.$nextTick(() => {
            this.scrollToBottom()
          })
        }
      } else {
        this.$message.error('发布失败: ' + result.message)
      }
    },
    
    addToRecentPublish() {
      const item = {
        topic: this.publishForm.topic,
        message: this.publishForm.message,
        qos: this.publishForm.qos,
        retain: this.publishForm.retain,
        timestamp: new Date().toISOString()
      }
      
      this.recentPublish.unshift(item)
      
      if (this.recentPublish.length > 10) {
        this.recentPublish = this.recentPublish.slice(0, 10)
      }
      
      // 保存到本地存储
      localStorage.setItem('mqtt_recent_publish', JSON.stringify(this.recentPublish))
    },
    
    loadFromHistory(item) {
      this.publishForm = {
        topic: item.topic,
        message: item.message,
        qos: item.qos || 0,
        retain: item.retain || false
      }
    },
    
    clearRecentPublish() {
      this.recentPublish = []
      localStorage.removeItem('mqtt_recent_publish')
    },
    
    formatJson() {
      try {
        const parsed = JSON.parse(this.publishForm.message)
        this.publishForm.message = JSON.stringify(parsed, null, 2)
      } catch (e) {
        this.$message.error('JSON 格式错误')
      }
    },
    
    formatMessage(message) {
      try {
        const parsed = JSON.parse(message)
        return JSON.stringify(parsed, null, 2)
      } catch (e) {
        return message
      }
    },
    
    formatTime(timestamp) {
      return new Date(timestamp).toLocaleTimeString()
    },
    
    truncateMessage(message, maxLength = 50) {
      if (message.length <= maxLength) return message
      return message.substring(0, maxLength) + '...'
    },
    
    applyTemplate(template) {
      this.publishForm.topic = template.topic
      this.publishForm.message = template.message
    },
    
    queryTopics(queryString, cb) {
      // 从订阅列表和最近发布中获取主题建议
      const topics = new Set()
      
      this.subscriptions.forEach(sub => topics.add(sub.topic))
      this.recentPublish.forEach(item => topics.add(item.topic))
      
      const results = Array.from(topics)
        .filter(topic => topic.toLowerCase().includes(queryString.toLowerCase()))
        .map(value => ({ value }))
      
      cb(results)
    },
    
    copyMessage(message) {
      navigator.clipboard.writeText(message).then(() => {
        this.$message.success('已复制到剪贴板')
      }).catch(() => {
        this.$message.error('复制失败')
      })
    },
    
    replyToMessage(msg) {
      this.publishForm.topic = msg.topic
      this.publishForm.message = ''
      this.$message.info('已设置回复主题')
    },
    
    clearMessages() {
      this.allMessages = []
      this.$store.dispatch('mqtt/clearMessages')
    },
    
    scrollToBottom() {
      const container = this.$refs.messagesList
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    }
  },
  mounted() {
    // 加载最近发布历史
    const saved = localStorage.getItem('mqtt_recent_publish')
    if (saved) {
      try {
        this.recentPublish = JSON.parse(saved)
      } catch (e) {
        console.error('Failed to load recent publish:', e)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../../styles/variables.scss';

.mqtt-client {
  .module-content {
    padding: $spacing-medium;
    height: calc(100vh - 200px);
  }
  
  .connection-card,
  .subscription-card,
  .messages-card,
  .publish-card {
    height: fit-content;
    
    .el-form-item:last-child {
      margin-bottom: 0;
    }
  }
  
  .messages-card {
    height: 100%;
    display: flex;
    flex-direction: column;
    
    ::v-deep .el-card__body {
      flex: 1;
      display: flex;
      flex-direction: column;
      padding: 0;
    }
  }
  
  .messages-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .header-actions {
      display: flex;
      align-items: center;
      gap: $spacing-small;
    }
  }
  
  .messages-list {
    flex: 1;
    overflow-y: auto;
    padding: $spacing-base;
    background: #f5f5f5;
    min-height: 500px;
    max-height: 600px;
    
    .message-item {
      background: #fff;
      border-radius: 4px;
      padding: $spacing-base;
      margin-bottom: $spacing-base;
      transition: all 0.3s;
      
      &.message-sent {
        border-left: 3px solid $success-color;
        background: rgba($success-color, 0.05);
      }
      
      &.message-received {
        border-left: 3px solid $primary-color;
      }
      
      &:hover {
        box-shadow: $box-shadow-light;
        
        .message-actions {
          opacity: 1;
        }
      }
      
      .message-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: $spacing-small;
        
        .message-meta {
          display: flex;
          align-items: center;
          gap: $spacing-small;
          
          .message-qos {
            font-size: $font-size-small;
            color: $text-secondary;
          }
        }
        
        .message-time {
          color: $text-secondary;
          font-size: $font-size-small;
        }
      }
      
      .message-body {
        pre {
          margin: 0;
          font-family: 'Monaco', 'Menlo', monospace;
          font-size: 12px;
          white-space: pre-wrap;
          word-wrap: break-word;
          color: $text-primary;
        }
      }
      
      .message-actions {
        margin-top: $spacing-small;
        opacity: 0;
        transition: opacity 0.3s;
      }
    }
  }
  
  .message-stats {
    padding: $spacing-small $spacing-base;
    background: #fafafa;
    border-top: 1px solid $border-color;
    font-size: $font-size-small;
    color: $text-secondary;
    display: flex;
    gap: $spacing-medium;
  }
  
  .subscriptions-list {
    margin-top: $spacing-medium;
    
    h4 {
      margin-bottom: $spacing-base;
      font-size: $font-size-small;
    }
    
    .subscription-tags {
      max-height: 150px;
      overflow-y: auto;
    }
    
    .empty-text {
      color: $text-secondary;
      text-align: center;
      padding: $spacing-base;
      font-size: $font-size-small;
    }
  }
  
  .quick-templates {
    margin-top: $spacing-medium;
    padding-top: $spacing-medium;
    border-top: 1px solid $border-color;
    
    h4 {
      margin-bottom: $spacing-base;
      font-size: $font-size-small;
    }
    
    .template-buttons {
      display: flex;
      flex-wrap: wrap;
    }
  }
  
  .recent-publish {
    margin-top: $spacing-medium;
    padding-top: $spacing-medium;
    border-top: 1px solid $border-color;
    
    h4 {
      margin-bottom: $spacing-base;
      font-size: $font-size-small;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .recent-list {
      max-height: 200px;
      overflow-y: auto;
    }
    
    .recent-item {
      padding: $spacing-small;
      margin-bottom: $spacing-small;
      background: $border-extra-light;
      border-radius: 4px;
      cursor: pointer;
      transition: background 0.3s;
      
      &:hover {
        background: $primary-light;
      }
      
      .recent-topic {
        font-weight: 500;
        font-size: $font-size-small;
        color: $text-primary;
        margin-bottom: 2px;
        
        i {
          color: $primary-color;
        }
      }
      
      .recent-message {
        font-size: 11px;
        color: $text-secondary;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }
  
  .empty-state {
    text-align: center;
    padding: $spacing-extra-large;
    color: $text-secondary;
    
    i {
      font-size: 48px;
      margin-bottom: $spacing-medium;
      color: $border-color;
    }
    
    p {
      margin: $spacing-small 0;
    }
    
    .empty-hint {
      font-size: $font-size-small;
      color: $text-placeholder;
    }
  }
}
</style>